package com.jiutong.meipengdai.ui.activitys;

import android.Manifest;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMapOptions;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.CoordinateConverter;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.base.BaseActivity;
import com.jiutong.meipengdai.entity.CityListRespond;
import com.jiutong.meipengdai.http.present.CommonPresent;
import com.jiutong.meipengdai.http.subscribers.SubscriberOnNextListener;
import com.jiutong.meipengdai.utils.DensityUtil;
import com.jiutong.meipengdai.utils.PermissionUtil;
import com.jiutong.meipengdai.views.popwindow.CitySelectPopupWindow;
import com.jiutong.meipengdai.views.popwindow.MapBottonPopupWindow;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by suxi on 2017/5/31.
 */

public class GaodeMapActivity extends BaseActivity implements AMap.OnMapLoadedListener, AMap.OnMarkerClickListener, AMap.OnMapTouchListener, LocationSource, AMapLocationListener, AMap.OnMapClickListener, AMap.OnCameraChangeListener, View.OnClickListener {

    public final int CITY = 3;
    public final int ZONE = 4;
    public final int STREET = 5;
    public final int VILLAGE = 6;
    private MapView mapView;
    private AMap aMap;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private UiSettings uiSettings;
    private int zoom_type = 10;
    private RelativeLayout rl_back;
    private MapBottonPopupWindow popupWindow;
    private View line;
    private CityListRespond respond;
    private Marker clickedMarker;
    private TextView tvOptions;
    private float oldZoom = zoom_type;
    private Marker cancelClickedMarker; //即将被取消选中效果的marker
    private View view_tag;
    private ImageView ivLoaction;
    private String city = "深圳市";
    private LatLonPoint myLocatioin; //定位点
    private LinearLayout rl_comment_title;
    private CitySelectPopupWindow citySelectPopupWindow;
    private List<CityListRespond.DataBean> dataList = new ArrayList<>();
    private List<CityListRespond.DataBean> levelCityList;//城市
    private List<CityListRespond.DataBean> levelZoneList;//区
    private List<CityListRespond.DataBean> levelStreetList;//街道
    private List<CityListRespond.DataBean> levelVillageList;//小区
    private int currentLevel = CITY;//数据层级
    private HashMap<String, CityListRespond.DataBean> selectedMarkerMap = new HashMap<>();//记录点击的marker附属的数据
    private String locationiCity;
    private boolean isShowLevelZone = false;

    /**
     * 將View转换成bitmap
     *
     * @param view
     * @return
     */
    public static Bitmap convertViewToBitmap(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_gaodemap;
    }

    @Override
    protected void initDate(Bundle savedInstanceState) {

        mapView = (MapView) findViewById(R.id.map);
        super.initDate(savedInstanceState);
        mapView.onCreate(savedInstanceState); // 此方法必须重写
//        new GaodeMapPresent(this, this).loadMarker();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        rl_back.setOnClickListener(this);
        tvOptions.setOnClickListener(this);
        ivLoaction.setOnClickListener(this);
    }

    @Override
    protected void initView() {
        super.initView();

        rl_comment_title = (LinearLayout) findViewById(R.id.rl_comment_title);
        tvOptions = (TextView) findViewById(R.id.tv_options);
        rl_back = (RelativeLayout) findViewById(R.id.rl_back);
        line = findViewById(R.id.view_line);
        view_tag = findViewById(R.id.view_tag);
        ivLoaction = (ImageView) findViewById(R.id.iv_location);

        setUpMap();
    }

    private void setUpMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }

        aMap.setOnMapLoadedListener(this);// 设置amap加载成功事件监听器
        aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
        aMap.setOnMapClickListener(this);
        aMap.setOnCameraChangeListener(this);

        // 设置定位监听
        aMap.setLocationSource(this);

//      设置定位图标样式
//       MyLocationStyle myLocationStyle = new MyLocationStyle();
//       myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.location_map));
//       aMap.setMyLocationStyle(myLocationStyle);

//      设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false

        aMap.setMyLocationEnabled(true);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(zoom_type)); //设置缩放比例
        uiSettings = aMap.getUiSettings();
        uiSettings.setZoomControlsEnabled(false);    //隐藏缩放按钮
//        uiSettings.setMyLocationButtonEnabled(true);  //显示定位按钮
        uiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT); //高德logo显示在右下方

        LatLng shenzhen = new LatLng(22.61667, 114.06667);//深圳坐标
        aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(shenzhen, zoom_type, 0, 0)));

        getLevelList(CITY, null);
    }

    /**
     * 添加层级marker
     */
    private void addLevelMarkers(int level) {

        aMap.clear();
        for (int i = 0; i < dataList.size(); i++) {

            LatLng latLng = new LatLng(Double.parseDouble(dataList.get(i).getLatitude()), Double.parseDouble(dataList.get(i).getLongitude()));
            View markerView = null;
            switch (level) {
                case CITY:
                case ZONE:
                case STREET:

                    markerView = View.inflate(mContext, R.layout.view_customer_marker, null);
                    break;
                case VILLAGE://小区显示不一样的marker
                    markerView = View.inflate(mContext, R.layout.view_customer_marker2, null);
                    break;
            }

            TextView tv_area = (TextView) markerView.findViewById(R.id.tv_area);
            TextView tv_price = (TextView) markerView.findViewById(R.id.tv_price);
            tv_area.setText(dataList.get(i).getAreaName());

            if (level == VILLAGE) {
                tv_price.setText((int) Float.parseFloat(dataList.get(i).getHousePerPrice()) + "");
            } else
                tv_price.setText((int) Float.parseFloat(dataList.get(i).getAveragePrice()) + "");

            Bitmap viewToBitmap = convertViewToBitmap(markerView);
            drawMarkerOnMap(covertLatlng(latLng), viewToBitmap, TextUtils.isEmpty(dataList.get(i).getAreaCode()) ? dataList.get(i).getId() : dataList.get(i).getAreaCode());
        }

    }

    /**
     * 删除marker并重新add一个背景激活的marker
     *
     * @param marker
     */
    private void changeMarkerBg(Marker marker, boolean isSelected) {
        View markerView = View.inflate(mContext, R.layout.view_customer_marker2, null);
        View rl_bg = markerView.findViewById(R.id.rl_bg);

        TextView tv_area = (TextView) markerView.findViewById(R.id.tv_area);
        TextView tv_price = (TextView) markerView.findViewById(R.id.tv_price);
        String areaCode = marker.getTitle();
        tv_area.setText(selectedMarkerMap.get(marker.getTitle()).getAreaName());
        tv_price.setText(selectedMarkerMap.get(marker.getTitle()).getHousePerPrice());

        if (isSelected) {
            rl_bg.setBackgroundResource(R.mipmap.marker_detail_bg_selected);
            tv_area.setTextColor(0xffffffff);
            tv_price.setTextColor(0xffffffff);
        } else {
            rl_bg.setBackgroundResource(R.mipmap.marker_detail_bg);
            tv_area.setTextColor(0xfff09738);
            tv_price.setTextColor(0xfff09738);
        }
        Bitmap viewToBitmap = convertViewToBitmap(markerView);
        drawMarkerOnMap(marker.getPosition(), viewToBitmap, areaCode);
        marker.remove();
    }

    @Override
    public void onMapLoaded() {
        Logger.d("onMapLoaded");
        //检查系统是否开启了地理位置权限;
        PermissionUtil.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {

        //一级marker点击事件
//        if (marker.getTitle().equals("1")) {
//            aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(marker.getPosition(), 14, 0, 0)));
//            return true;
//        }

        if (currentLevel != VILLAGE) {
            currentLevel++;
            getLevelList(currentLevel, marker.getTitle());
            switch (currentLevel) {
                case ZONE:
                    aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(marker.getPosition(), 12, 0, 0)));
                    break;
                case STREET:
                    aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(marker.getPosition(), 14, 0, 0)));
                    break;
                case VILLAGE:
                    aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(marker.getPosition(), 16, 0, 0)));
                    break;

            }
            return true;
        }

        if (clickedMarker != null && clickedMarker != marker) {//如果当前点击的marker跟上一次点击不是相同的marker，那么上次点击的marker要改变为非选中状态
            cancelClickedMarker = clickedMarker;
            changeMarkerBg(cancelClickedMarker, false);
        }

        clickedMarker = marker;

        showBottomPop(marker);
        changeMarkerBg(marker, true);
        moveToNewCenter(marker);
        return true;
    }

    /**
     * 将点击的marker移动到地图没有被遮盖的区域中心, 这种是改变地图中心，然后移动地图，另一种实现方式可以通过算好距离直接平移
     *
     * @param marker
     */
    private void moveToNewCenter(Marker marker) {
        WindowManager wm = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);
        int screenWidth = wm.getDefaultDisplay().getWidth();
        int screenHeight = wm.getDefaultDisplay().getHeight();

        int distanceForScreen = popupWindow.getDistanceForScreen(); //得到pop到顶端距离

        //distanceforScreen 第一次获取的时候会为零，因为pop还没有完全执行完动画,view_tag只是作為参照物存在
        if (distanceForScreen == 0) {
            distanceForScreen = view_tag.getTop();
        }

        int mapY = distanceForScreen - DensityUtil.dip2px(mContext, 48);//地图Y轴可视区域  48位title的高度
        int mapDisplayAreaCenterY = mapY / 2 + DensityUtil.dip2px(mContext, 48);//得到地图可是区域Y轴中心

        int mapDisplayAreaCenterX = screenWidth / 2;

        //地图可见区域中心位置
        Point newDisplayAreaCenterPoint = new Point();
        newDisplayAreaCenterPoint.set(mapDisplayAreaCenterX, mapDisplayAreaCenterY);
        //将新的中心点转换成地图坐标
        LatLng newCenterLatLng = aMap.getProjection().fromScreenLocation(newDisplayAreaCenterPoint);

        //获取原来中心点坐标
        Point oldCenterPoint = new Point();
        int oldCenterX = mapDisplayAreaCenterX;
        int oldCenterY = (screenHeight - DensityUtil.dip2px(mContext, 48)) / 2;
        oldCenterPoint.set(oldCenterX, oldCenterY);

        //将原来的中心点转换成地图坐标
        LatLng oldCenterLatLng = aMap.getProjection().fromScreenLocation(oldCenterPoint);

        LatLng markerPosition = marker.getPosition();
        //算出地图应该经纬度的偏移量
        double dx = oldCenterLatLng.latitude - newCenterLatLng.latitude;
        double dy = oldCenterLatLng.longitude - newCenterLatLng.longitude;

        //得到新中心点位置
        LatLng newCenter = new LatLng(markerPosition.latitude + dx, markerPosition.longitude + dy);

        aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(newCenter, oldZoom, 30, 0)), 200, null);
//        aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(newCenter, 14, 30, 0)));
    }

    private void showBottomPop(Marker marker) {
        if (popupWindow == null) {
            popupWindow = new MapBottonPopupWindow(mContext);
            popupWindow.setmPopAlpha(0);
            popupWindow.setOnBtnClickLister(new MapBottonPopupWindow.OnPingGuBtnClickLister() {
                @Override
                public void onLiJiBtnClick() {
                }

                @Override
                public void onKeepPgclick() {

                }

                @Override
                public void onOtherPgClick() {
                    openActivity(EvaluateActivity.class);
                }
            });
        }

        CityListRespond.DataBean dataBean = selectedMarkerMap.get(marker.getTitle());
        popupWindow.getTvHouseName().setText(dataBean.getAreaName());
        popupWindow.getTvPrice().setText(dataBean.getHousePerPrice());
        popupWindow.getTvAddress().setText(dataBean.getMergerName());
        popupWindow.showPopupWindow(line, Gravity.BOTTOM);
    }

    @Override
    public void onTouch(MotionEvent motionEvent) {
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    protected void getLevelList(final int level, String areaCode) {

        switch (level) {
            case CITY:

                CommonPresent.getCityData(mContext, new SubscriberOnNextListener<CityListRespond>() {
                    @Override
                    public void onNext(CityListRespond respond) {
                        if ("200".equals(respond.getResCode())) {
                            levelCityList = respond.getData();
                            dataList.addAll(levelCityList);

                            if (locationiCity != null) {
                                for (CityListRespond.DataBean city : levelCityList) {
                                    if (city.getAreaName().contains(locationiCity)) {
                                        getLevelList(ZONE, city.getAreaCode());
                                        aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(myLocatioin.getLatitude(), myLocatioin.getLongitude()), 12, 0, 0)));
                                        isShowLevelZone = true;
                                    }
                                }
                            } else {
                                addLevelMarkers(level);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }, null);

                break;
            case ZONE:
            case STREET:
            case VILLAGE:

                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("id", areaCode);
                hashMap.put("resultAreaType", "" + level);
                CommonPresent.getAreaAndStreedList(mContext, new SubscriberOnNextListener<CityListRespond>() {
                    @Override
                    public void onNext(CityListRespond respond) {
                        if ("200".equals(respond.getResCode())) {

                            dataList.clear();
                            if (level == ZONE) {
                                levelZoneList = respond.getData();
                                levelStreetList = null;
                                levelVillageList = null;
                                dataList.addAll(levelZoneList);
                            } else if (level == STREET) {
                                levelStreetList = respond.getData();
                                levelVillageList = null;
                                dataList.addAll(levelStreetList);
                            } else if (level == VILLAGE) {
                                levelVillageList = respond.getData();
                                dataList.addAll(levelVillageList);

                                for (CityListRespond.DataBean dataBean :
                                        levelVillageList) {
                                    selectedMarkerMap.put(dataBean.getId(), dataBean);
                                }
                            }
                            addLevelMarkers(level);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }, hashMap);
                break;
        }

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();//启动定位
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                double latitude = aMapLocation.getLatitude();
                double longitude = aMapLocation.getLongitude();

                myLocatioin = new LatLonPoint(latitude, longitude);


                if (isShowLevelZone)
                    return;

                /**
                 * 逆地理编码
                 */
                GeocodeSearch geocodeSearch = new GeocodeSearch(this);
                geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                    @Override
                    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                        locationiCity = regeocodeResult.getRegeocodeAddress().getCity();

                        if (levelCityList != null) {
                            for (CityListRespond.DataBean city : levelCityList
                                    ) {
                                if (city.getAreaName().contains(locationiCity)) {
                                    currentLevel = ZONE;
                                    getLevelList(ZONE, city.getAreaCode());
                                    aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(myLocatioin.getLatitude(), myLocatioin.getLongitude()), 12, 0, 0)));
                                    isShowLevelZone = true;
                                }
                            }
                        }
//                        Logger.d("地位地址：locationiCity == " + locationiCity);
                    }

                    @Override
                    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

                    }
                });

                // 第一个参数表示一个Latlng(经纬度)，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
                RegeocodeQuery query = new RegeocodeQuery(myLocatioin, 200, GeocodeSearch.AMAP);
                geocodeSearch.getFromLocationAsyn(query);

            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Logger.e("AmapErr", errText);
            }
        }
    }

    @Override
    public void onMapClick(LatLng latLng) {
    }

    private Marker drawMarkerOnMap(LatLng point, Bitmap markerIcon, String areaCode) {

        if (aMap != null && point != null) {

            Marker marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 1)
                    .position(point)
                    .title(areaCode)
                    .icon(BitmapDescriptorFactory.fromBitmap(markerIcon)));

            return marker;
        }
        return null;
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        float zoom = cameraPosition.zoom;

//        if (oldZoom == zoom) {
//            return;
//        }

        if (dataList == null) {
            return;
        }

        if (zoom > 14 && currentLevel != VILLAGE) {//显示小区
            if (levelVillageList != null && levelVillageList.size() > 0) {
                dataList.clear();
                currentLevel = VILLAGE;
                dataList.addAll(levelVillageList);
                addLevelMarkers(currentLevel);
            }
        } else if (zoom > 12 && zoom <= 14 && currentLevel != STREET) {//显示街道
            if (levelStreetList != null && levelStreetList.size() > 0) {
                dataList.clear();
                currentLevel = STREET;
                dataList.addAll(levelStreetList);
                addLevelMarkers(currentLevel);
            }

        } else if (zoom > 10 && zoom <= 12 && currentLevel != ZONE) {//显示区
            if (levelZoneList != null && levelZoneList.size() > 0) {
                currentLevel = ZONE;
                dataList.clear();
                dataList.addAll(levelZoneList);
                addLevelMarkers(currentLevel);
            }

        } else if (zoom <= 10 && currentLevel != CITY) {//显示城市
            if (levelCityList != null && levelCityList.size() > 0) {
                dataList.clear();
                currentLevel = CITY;
                dataList.addAll(levelCityList);
                addLevelMarkers(currentLevel);
            }
        }

//        Logger.d("currentLevel == " + currentLevel + "zoom == " + zoom);

//        if (clickedMarker != null && currentLevel == VILLAGE) {
//            changeMarkerBg(clickedMarker, true);
//        }
        oldZoom = zoom;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_back:
                if (citySelectPopupWindow != null && citySelectPopupWindow.isShowing()) {
                    citySelectPopupWindow.backUp();
                } else {
                    finish();
                }
                break;
            case R.id.tv_options:

                if (citySelectPopupWindow != null && citySelectPopupWindow.isShowing()) {
                    citySelectPopupWindow.dismiss();
                    Drawable dra = getResources().getDrawable(R.mipmap.icon_arrow_down);
                    dra.setBounds(0, 0, dra.getMinimumWidth(), dra.getMinimumHeight());
                    tvOptions.setCompoundDrawables(null, null, dra, null);
                    return;
                }

                citySelectPopupWindow = new CitySelectPopupWindow(mContext);

                citySelectPopupWindow.setCallBack(new CitySelectPopupWindow.PopCallBack() {
                    @Override
                    public void callBack(HashMap<String, CityListRespond.DataBean> map, List<CityListRespond.DataBean> cityList, List<CityListRespond.DataBean> zoneList, List<CityListRespond.DataBean> streetList) {
                        CityListRespond.DataBean level_one = map.get("level_one");
                        CityListRespond.DataBean level_two = map.get("level_two");
                        CityListRespond.DataBean level_three = map.get("level_three");

                        levelCityList = cityList;
                        levelZoneList = zoneList;
                        levelStreetList = streetList;
                        CityListRespond.DataBean clickTab = null;
                        int scaleZoom = 10;

                        dataList.clear();

                        if (level_three == null && level_two != null) {
                            currentLevel = ZONE;
                            clickTab = level_two;
                            dataList.addAll(levelZoneList);
                            scaleZoom = 12;
                            tvOptions.setText(level_one.getAreaName() + level_two.getAreaName());
                        }

                        if (level_two == null && level_one != null) {
                            currentLevel = CITY;
                            dataList.addAll(levelCityList);
                            clickTab = level_one;
                            tvOptions.setText(level_one.getAreaName());
                        }

                        if (level_two != null && level_three != null) {
                            clickTab = level_three;
                            currentLevel = STREET;
                            scaleZoom = 14;
                            dataList.addAll(levelStreetList);
                            tvOptions.setText(level_one.getAreaName() + level_two.getAreaName() + level_three.getAreaName());
                        }

                        //移动到点击的位置
                        aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(covertLatlng(new LatLng(Double.parseDouble(clickTab.getLatitude()), Double.parseDouble(clickTab.getLongitude()))), scaleZoom, 0, 0)));
//                        getLevelList(currentLevel, clickTab.getAreaCode());
                        addLevelMarkers(currentLevel);
                    }

                    @Override
                    public void dimissCallBack() {

                        Drawable dra = getResources().getDrawable(R.mipmap.icon_arrow_down);
                        dra.setBounds(0, 0, dra.getMinimumWidth(), dra.getMinimumHeight());
                        tvOptions.setCompoundDrawables(null, null, dra, null);
                    }
                });

                citySelectPopupWindow.showPopupWindow(line, Gravity.TOP);

                Drawable dra = getResources().getDrawable(R.mipmap.icon_arrow_up);
                dra.setBounds(0, 0, dra.getMinimumWidth(), dra.getMinimumHeight());
                tvOptions.setCompoundDrawables(null, null, dra, null);
                break;
            case R.id.iv_location:
                if (myLocatioin != null) {

                    aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(myLocatioin.getLatitude(), myLocatioin.getLongitude()), oldZoom, 30, 0)), 500, null);
                } else {
                    toastShortShow("请开启地图权限");
                }
                break;
        }
    }

    /**
     * 百度坐标转换高德坐标
     *
     * @param latLng
     * @return
     */
    public LatLng covertLatlng(LatLng latLng) {
        CoordinateConverter converter = new CoordinateConverter();
        // CoordType.GPS 待转换坐标类型
        converter.from(CoordinateConverter.CoordType.BAIDU);
        // sourceLatLng待转换坐标点 LatLng类型
        converter.coord(latLng);
        // 执行转换操作
        return converter.convert();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (citySelectPopupWindow != null && citySelectPopupWindow.isShowing()) {
                citySelectPopupWindow.backUp();
                return false;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
}
